<?php

/**
 *
 * @author lovebing <lovebing365@126.com> Created on 2014-10-6 10:46:59
 */
class XML {

    public static function xmlToArray($xml) {
        $array = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array;
    }

    public static function arrayToXml(array $data, $root = true) {
        $xml = '';
        if ($root) {
            $xml .= '<xml>';
        }
        foreach ($data as $k => $v) {
            if (is_array($v)) {
                $v = self::arrayToXml($v, false);
            }
            elseif (!is_numeric($v)) {
                $v = '<![CDATA[' . $v . ']]>';
            }
            $xml .= '<' . $k . '>' . $v . '</' . $k . '>';
        }
        if ($root) {
            $xml .= '</xml>';
        }
        return $xml;
    }

}
